import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class JDBC {
    public static void main(String[] args) throws SQLException {
        //1.创建数据源
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setURL("jdbc:mysql://127.0.0.1:3306/java102?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("123456");

        //2.建立连接
        Connection connection = dataSource.getConnection();

        //3.让用户通过控制台输入下一个带插入的数据
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入学号：");
        int id = scanner.nextInt();
        System.out.println("请输入姓名：");
        String name = scanner.next();

        //4.操作数据库
        String str = "insert into student values(?, ?)";
        PreparedStatement preparedStatement = connection.prepareStatement(str);
        preparedStatement.setInt(1,id);
        preparedStatement.setString(2,name);
        System.out.println("prepareStatement: " + preparedStatement);

        //5.执行SQL，相当于扫码取件
        int ret = preparedStatement.executeUpdate();
        System.out.println(ret);

        //6.此时SQL执行完毕，需要释放资源
        preparedStatement.close();
        connection.close();
    }
}
